//
//  LLSegmentView.m
//  TaoTuo
//
//  Created by admin on 2019/11/4.
//  Copyright © 2019 admin. All rights reserved.
//

#import "LLSegmentView.h"

static NSMutableDictionary *widthDic;

@interface LLSegmentView ()

@property (nonatomic, strong) NSArray *itemsArray;

@property (nonatomic, strong) NSMutableArray *lineArray;
@property (nonatomic, strong) NSMutableArray *itemsBtnAttay;

@property (nonatomic, strong) UIFont *font;
@property (nonatomic, strong) UIFont *selectFont;
@property (nonatomic, strong) UIColor *normalColor;
@property (nonatomic, strong) UIColor *selectColor;
@property (nonatomic, strong) NSArray *selectItems;
@property (nonatomic, strong) NSMutableArray *widthArray;   //宽度数组
@property (nonatomic, strong) UIButton *selectBtn;  // 选中的那个按钮

@property (nonatomic, copy) SelectItemBlock selectItemBlock;

@end

@implementation LLSegmentView

- (instancetype)initWithFrame:(CGRect)frame items:(NSArray *)items selectItemBlock:(nonnull SelectItemBlock)selectItemBlock
{
    self = [super initWithFrame:frame];
    if (self) {
        self.itemsArray = items;
        if (items.count > 0) {
            self.lineArray = [NSMutableArray array];
            self.itemsBtnAttay = [NSMutableArray array];
            self.widthArray = [NSMutableArray array];
            widthDic = [NSMutableDictionary dictionary];
            self.selectItemBlock = selectItemBlock;
            
            [self setupSubviews];
        }
    }
    
    return self;
}

- (void)clickItemAction:(UIButton *)sender
{
    if (sender == self.selectBtn) {
        return;
    }
    
    NSInteger index = [self.itemsBtnAttay indexOfObject:sender];
    
    id firstObj = self.itemsArray.firstObject;
    
    if ([firstObj isKindOfClass:[UIImage class]]) {
        if (self.selectItemBlock) {
            self.selectItemBlock(index, sender);
        }
        return;
    }
    
    sender.selected = YES;
    self.selectBtn.selected = NO;
    self.selectBtn = sender;
    
    NSString *selKey = [NSString stringWithFormat:@"%ld_sel", index];
    
    [UIView animateWithDuration:0.2 animations:^{
        CGFloat left = 0;
        for (int i = 0; i < self.itemsBtnAttay.count; i++) {
            CGFloat w;
            if (i != index) {
                NSString *key = [NSString stringWithFormat:@"%d", i];
                w = [widthDic[key] floatValue];
                
            } else {
                w = [widthDic[selKey] floatValue];
            }
            
            UIButton *btn = self.itemsBtnAttay[i];
            btn.frame = CGRectMake(left, 0, w, self.frame.size.height);
            
            if (self.lineArray.count > 0) {
                if (i > 0 && i < self.itemsBtnAttay.count) {
                    UIView *lineView = self.lineArray[i - 1];
                    lineView.frame = CGRectMake(left, 8, 1, self.frame.size.height - 16);
                }
            }
            
            left += w;
        }
        CGRect frame = self.frame;
        frame.size.width = left;
        self.frame = frame;
        
    }];
    
//    NSLog(@"点击了== %ld", index);
    if (self.selectItemBlock) {
        self.selectItemBlock(index, sender);
    }
}

/// 设置字体大小
- (void)setFont:(UIFont *)font
{
    _font = font;
    [self setItems:self.itemsArray btnFont:font forState:UIControlStateNormal];
}

/// 设置选中的字体大小
- (void)setSelectFont:(UIFont *)selectFont
{
    _selectFont = selectFont;
    NSArray *arr = self.selectItems.count > 0 ? self.selectItems : self.itemsArray;
    [self setItems:arr btnFont:selectFont forState:UIControlStateSelected];
    
}

/// 设置字体颜色
- (void)setTitleColor:(UIColor *)titleColor
{
    _normalColor = titleColor;
    for (UIButton *btn in self.itemsBtnAttay) {
        NSAttributedString *attr = [btn attributedTitleForState:UIControlStateNormal];
        NSMutableAttributedString *mAttr = [[NSMutableAttributedString alloc] initWithAttributedString:attr];
        [mAttr addAttribute:NSForegroundColorAttributeName value:titleColor range:NSMakeRange(0, attr.string.length)];
        [btn setAttributedTitle:mAttr forState:UIControlStateNormal];
    }
}

/// 设置选中的字体颜色
- (void)setSelectTitleColor:(UIColor *)selectTitleColor
{
    _selectColor = selectTitleColor;
    for (UIButton *btn in self.itemsBtnAttay) {
        NSAttributedString *attr = [btn attributedTitleForState:UIControlStateSelected];
        NSMutableAttributedString *mAttr = [[NSMutableAttributedString alloc] initWithAttributedString:attr];
        [mAttr addAttribute:NSForegroundColorAttributeName value:selectTitleColor range:NSMakeRange(0, attr.string.length)];
        [btn setAttributedTitle:mAttr forState:UIControlStateSelected];
        
    }
}

/// 设置选中的item
- (void)setSelectItems:(nullable NSArray *)selectItems
{
    NSAssert(selectItems.count == self.itemsBtnAttay.count, @"选中item的个数应与初始化时的item个数相等");
    _selectItems = selectItems;
    
    id firstObj = selectItems.firstObject;
    
    if ([firstObj isKindOfClass:[UIImage class]]) {
        for (int i = 0; i < selectItems.count; i++) {
            UIImage *image = selectItems[i];
            UIButton *btn = self.itemsBtnAttay[i];
            [btn setImage:image forState:UIControlStateSelected];
        }
    } else {
        for (int i = 0; i < selectItems.count; i++) {
            UIButton *btn = self.itemsBtnAttay[i];
            UIFont *font = self.selectFont ? : (self.font ? : btn.titleLabel.font);
            [self setItems:selectItems btnFont:font forState:UIControlStateSelected];
        }
    }
}


- (void)setItems:(NSArray *)itemsArray btnFont:(UIFont *)font forState:(UIControlState)state
{
    id firstObj = itemsArray.firstObject;
    
    if ([firstObj isKindOfClass:[UIImage class]]) {
        return;
    }
    
    CGFloat left = 0;
    for (int i = 0; i < itemsArray.count; i++) {
        UIButton *btn = self.itemsBtnAttay[i];
        NSString *title = itemsArray[i];
        NSAttributedString *attribute = [btn attributedTitleForState:state];
        NSDictionary *dic = [attribute attributesAtIndex:0];
        NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:title];
        // 添加颜色
        if (dic[@"NSColor"]) {
            [attrStr addAttribute:NSForegroundColorAttributeName value:dic[@"NSColor"] range:NSMakeRange(0, title.length)];
        }
        [attrStr addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, title.length)];
        [btn setAttributedTitle:attrStr forState:state];
        CGFloat titleW = [title boundingRectWithSize:CGSizeMake(MAXFLOAT, self.frame.size.height) options:NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName : font} context:nil].size.width + 10;
        // 保存宽度
        NSString *key = state == UIControlStateNormal ? [NSString stringWithFormat:@"%d", i] : [NSString stringWithFormat:@"%d_sel", i];
        [widthDic setObject:@(titleW) forKey:key];
        
        if (state == UIControlStateNormal) {
            btn.frame = CGRectMake(left, 0, titleW, self.frame.size.height);
            if (self.lineArray.count > 0) {
                if (i > 0 && i < itemsArray.count) {
                    UIView *lineView = self.lineArray[i - 1];
                    lineView.frame = CGRectMake(left, 8, 1, self.frame.size.height - 16);
                }
            }
            
            left += titleW;
        }
        
    }
    if (state == UIControlStateNormal) {
        CGRect frame = self.frame;
        frame.size.width = left;
        self.frame = frame;
    }
    
}


- (void)setItems:(NSArray *)items
{
    self.itemsArray = items;
    [self.itemsBtnAttay removeAllObjects];
    
    [self removeAllSubviews];
    
    [self setupSubviews];
}

- (void)setupSubviews
{
    id firstObj = self.itemsArray.firstObject;
    
    if ([firstObj isKindOfClass:[UIImage class]]) {
        
        CGFloat itemW = self.frame.size.width / self.itemsArray.count;
        for (int i = 0; i < self.itemsArray.count; i++) {
            UIImage *image = self.itemsArray[i];
            // 按钮
            UIButton *itemBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            itemBtn.frame = CGRectMake(itemW * i, 0, itemW, self.frame.size.height);
            [itemBtn setImage:image forState:UIControlStateNormal];
            [itemBtn addTarget:self action:@selector(clickItemAction:) forControlEvents:UIControlEventTouchUpInside];
            [self addSubview:itemBtn];
            // 线条
            if (i > 0 && i < self.itemsArray.count) {
                UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(itemW * i, 8, 1, self.frame.size.height - 16)];
                lineView.backgroundColor = UIColorHex(EEEEEE);
                [self addSubview:lineView];
            }
            
            [self.itemsBtnAttay addObject:itemBtn];
            
        }
        
    } else {
        CGFloat left = 0;
        for (int i = 0; i < self.itemsArray.count; i++) {
            NSString *title = self.itemsArray[i];
            UIFont *font = [UIFont systemFontOfSize:14];
            CGFloat titleW = [title boundingRectWithSize:CGSizeMake(MAXFLOAT, self.frame.size.height) options:NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName : font} context:nil].size.width + 10;

            // 保存宽度
            NSString *normalKey = [NSString stringWithFormat:@"%d", i];
            NSString *selectKey = [NSString stringWithFormat:@"%d_sel", i];
            [widthDic setObject:@(titleW) forKey:normalKey];
            [widthDic setObject:@(titleW) forKey:selectKey];
            
            NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:title];
            [attrStr addAttributes:@{NSFontAttributeName : font} range:NSMakeRange(0, title.length)];
            // 按钮
            UIButton *itemBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            itemBtn.frame = CGRectMake(left, 0, titleW, self.frame.size.height);
            [itemBtn setAttributedTitle:attrStr forState:UIControlStateNormal];
            [itemBtn addTarget:self action:@selector(clickItemAction:) forControlEvents:UIControlEventTouchUpInside];
            [self addSubview:itemBtn];
            // 线条
            if (i > 0 && i < self.itemsArray.count) {
                UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(left, 8, 1, self.frame.size.height - 16)];
                lineView.backgroundColor = UIColorHex(EEEEEE);
                [self addSubview:lineView];
                [self.lineArray addObject:lineView];
            }
            left += titleW;
            
            [self.itemsBtnAttay addObject:itemBtn];
            
        }
        
        CGRect frame = self.frame;
        frame.size.width = left;
        self.frame = frame;
    }
}



@end
